package com.weigang.webservice.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.weigang.webservice.exception.R;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

@RestController
public class WsdlTestController {

    @GetMapping({"checkUser"})
    public Object checkUser(@RequestParam(value = "sex") Integer sex,
                       @RequestParam(value = "IDCard") String IDCard) throws Exception {
        String methodName = "M_TestSexAndIDCard操作";
        String urlAddress = "http://192.168.50.120:8095/DataIntegrationService/WebService/Web_%E6%9C%8D%E5%8A%A1/";

        //第一步：创建服务地址，也就是提供的WSDL的接口地址
        URL url = new URL(urlAddress);
        //第二步：打开一个通向服务地址的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //第三步：设置参数
        //3.1发送方式设置：POST必须大写
        connection.setRequestMethod("POST");
        //3.2设置数据格式：content-type
        connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
        //3.3设置输入输出，因为默认新创建的connection没有读写权限，
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //第四步：组织SOAP数据，发送请求，
        String soapXML = getXML(methodName, sex, IDCard);
        //将信息以流的方式发送出去
        OutputStream os = connection.getOutputStream();
        os.write(soapXML.getBytes());
        //第五步：接收服务端响应，打印
        int responseCode = connection.getResponseCode();
        if (200 == responseCode) {//表示服务端响应成功
            //获取当前连接请求返回的数据流
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            StringBuilder sb = new StringBuilder();
            String temp = null;
            while (null != (temp = br.readLine())) {
                sb.append(temp);
            }
            System.out.println("---" + sb.toString());
            try {
                //对返回的数据进行JSON格式化
                System.out.println(xml2Json(sb.toString()));
                return xml2Json(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                is.close();
                isr.close();
                br.close();
            }

        }
        os.close();
        return "数据错误";
    }



    //请求入参
    public static String getXML(String methodName,int sex,String IDCard){
        String soapXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://www.informatica.com/dis/ws/Web_s\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <web:"+ methodName +">\n" +
                "         <!--Zero or more repetitions:-->\n" +
                "         <web:组>\n" +
                "            <!--Optional:-->\n" +
                "            <web:sex>"+ sex +"</web:sex>\n" +
                "            <!--Optional:-->\n" +
                "            <web:idcard>"+IDCard+"</web:idcard>\n" +
                "         </web:组>\n" +
                "      </web:" + methodName + ">\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        return soapXML;
    }



    /**
     * xml转json
     *
     * @param xmlStr
     * @return
     * @throws DocumentException
     */
    public static JSONObject xml2Json(String xmlStr) throws DocumentException {
        Document doc = DocumentHelper.parseText(xmlStr);
        JSONObject json = new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    /**
     * xml转json
     *
     * @param element
     * @param json
     */
    public static void dom4j2Json(Element element, JSONObject json) {
        List<Element> chdEl = element.elements();
        for(Element e : chdEl){
            if (!e.elements().isEmpty()) {
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
            } else {
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }
}
